<template>
  <span v-if="editMode" class="simple-date">
    <el-date-picker
      v-bind="$attrs"
      value-format="x"
      @clear="() => $emit('update:modelValue', '')"
    />
  </span>
  <div class="simple-text" v-else :style="`justify-content: ${textAlign}`">
    {{ format($attrs.modelValue as string) }}
    <el-link
      v-if="$attrs.modelValue && showCopy"
      class="copy-link"
      :underline="false"
      @click="copyText(format($attrs.modelValue as string))"
    >
      <el-icon>
        <DocumentCopy />
      </el-icon>
      <span class="text">{{ t('common.clickCopy') }}</span>
    </el-link>
  </div>
</template>

<script setup lang="ts">
import { useClipboard } from '@vueuse/core'
import { DocumentCopy } from '@element-plus/icons-vue'
import { formatDate } from '@/utils/formatTime'

const props = defineProps({
  formatter: {
    type: String,
    default: 'YYYY-MM-DD'
  },
  showCopy: {
    type: Boolean,
    default: true
  },
  textAlign: {
    type: String,
    default: 'flex-start'
  }
})

const editMode = inject('editMode', true)

const message = useMessage()
const { t } = useI18n()
const { copy } = useClipboard()

const copyText = async (text: string) => {
  try {
    await copy(text)
    message.success(t('common.copySuccess'))
  } catch (e) {
    message.error(t('common.copyError'))
  }
}

const format = (value: string) => {
  return formatDate(value, props.formatter)
}
</script>

<style scoped lang="scss">
.simple-date {
  flex-grow: 1;

  :deep(.el-input) {
    width: 100%;
  }

  :deep(.el-input__wrapper) {
    border-radius: 0 !important;
    box-shadow: none !important;
    padding: 0 !important;
    border-bottom: 1px solid var(--el-border-color);
  }

  :deep(.el-input__suffix) {
    position: absolute;
    right: 0;
  }

  :deep(.el-input__suffix-inner) {
    width: 22px;
  }
}

.simple-text {
  display: flex;
  align-items: center;

  .copy-link {
    visibility: hidden;
    margin-left: 6px;

    .text {
      font-size: 12px;
      visibility: hidden;
    }

    &:hover {
      .text {
        visibility: visible;
      }
    }
  }

  &:hover {
    .copy-link {
      visibility: visible;
    }
  }
}
</style>
